﻿using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Data;
using Xm.Entity;
using Xm.Models;

namespace Xm.Controllers
{

    public class TextController : Controller
    {
        private readonly ITestLogin _textlogin; // 建议使用 readonly 字段

        public TextController(ITestLogin textlogin) // 构造函数注入
        {
            _textlogin = textlogin;
        }

        [HttpGet] // 添加明确的路由
        public async Task<IActionResult> GetJobCascaderData()
        {
            try
            {
                // 直接返回服务层处理好的数据，无需再次转换
                var cascaderData = await _textlogin.GetJobCascaderDataAsync1();
                return Ok(cascaderData);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取职位级联数据失败: {ex.Message}");
                return StatusCode(500, "获取职位数据失败");
            }
        }

        [HttpGet]
        public async Task<IActionResult> releaseUpdate()
        {

            return View();
        }
        [HttpPost]
        [HttpPut] // 同时支持POST和PUT
        [Route("Text/releaseUpdate")]
        public async Task<IActionResult> releaseUpdate([FromBody] engage_major_release dz) // 修正类型
        {
            try
            {
                if (dz == null)
                {
                    return BadRequest(new { success = false, message = "数据为空" });
                }

                // 判断是新增还是修改（根据fsk_id是否有值）
                bool isUpdate = dz.mre_id > 0;
                int result = 0;

                if (isUpdate)
                {
                    result = await _textlogin.update(dz); // 修改操作
                }
                else
                {
                    // 新增操作（需要在_text中添加对应的新增方法）
                    result = await _textlogin.update(dz);
                }

                return result > 0
                    ? Ok(new { success = true, message = isUpdate ? "修改成功" : "新增成功" })
                    : Ok(new { success = false, message = isUpdate ? "修改失败" : "新增失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        public IActionResult Index1()
        {
            return View();
        }
        public IActionResult Update()
        {
            return View();
        }
        public IActionResult Updatefy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "mre_id");
                param.Add("@keyName", "engage_major_release");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<engage_major_release> list = conn.Query<engage_major_release>(sql, param).ToList();

                FenYe<engage_major_release> fenYecs = new FenYe<engage_major_release>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }
        }
        [HttpGet]
        public async Task<IActionResult> Delete()
        {

            return View();
        }
        
        public async Task<IActionResult> Delete(int id)
        {

            var rowsAffected = await _textlogin.Delete(id);
            if (rowsAffected > 0)
            {
                return RedirectToAction("Update");
            }
            else
            {
                return RedirectToAction("Update");
            }


        }
        public IActionResult Update1()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] users model) // 使用模型类绑定JSON
        {
            try
            {
                if (model == null ||
                    string.IsNullOrEmpty(model.u_true_name?.Trim()) ||
                    string.IsNullOrEmpty(model.u_password?.Trim()))
                {
                    return BadRequest("用户名和密码不能为空");
                }

                int result = await _textlogin.Login(
                    model.u_true_name.Trim(),
                    model.u_password.Trim()
                );

                if (result > 0)
                {
                    return Ok(new { success = true, message = "登录成功" });
                }
                else
                {
                    return Ok(new { success = false, message = "用户名或密码错误" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, "登录过程中发生错误，请稍后再试");
            }
        }
        

        // 处理表单提交的POST方法
       
            
        
            [HttpGet]
            public async Task<IActionResult> insert()
            {

                return View();
            }
        
            [HttpPost]
            [Route("Text/insert")]
            public async Task<IActionResult> insert([FromBody] engage_major_release dz)
            {
                try
                {
                    // 添加日志，确认方法是否被调用
                    Console.WriteLine($"接收到插入请求: {JsonConvert.SerializeObject(dz)}");

                    int i = await _textlogin.insert(dz);
                    if (i > 0)
                    {
                        return Ok(new { success = true, message = "添加成功" });
                    }
                    else
                    {
                        return Ok(new { success = false, message = "插入失败" });
                    }
                }
                catch (Exception ex)
                {
                    // 添加异常处理，记录详细错误
                    Console.WriteLine($"插入异常: {ex.Message}");
                    return StatusCode(500, new { success = false, message = "服务器错误" });
                }
            }
    }
}
